package com.google.code.tretris.rendering;



import com.google.code.tretris.common.Tetromino;
import com.google.code.tretris.events.UpdateBoardEvent;

public class Shape extends MVComplexObject {

	protected int rotation = 0;
	private Tetromino tetromino;
	private float[] color;

	public Shape() {
		children.add(new Cube(Cube.DEFAULT_WIDTH));
		children.add(new Cube(Cube.DEFAULT_WIDTH));
		children.add(new Cube(Cube.DEFAULT_WIDTH));
		children.add(new Cube(Cube.DEFAULT_WIDTH));
	}

	public void setTetromino(final Tetromino tetromino) {
		this.tetromino = tetromino;	
	}

	public void move(final int deltaX) {
		if (deltaX > 0) {
			x++;
		} else if (deltaX < 0) {
			x--;
		}
	}

	public synchronized void setRotation(int rotation) {
		this.rotation = rotation;
	}
	
	public synchronized int getRotation() {
		return rotation; 
	}

	public float[] getColor() {
		return Tetromino.COLORS.get(tetromino.code) ;
	}

	public void update(final UpdateBoardEvent e) {
		this.rotation = e.getRotation();
		this.tetromino = Tetromino.getFromChar(e.getTetromino());
		this.color = getColor();
		setColor(color[0], color[1], color[2]);
		this.x = e.getX(); 
		this.y = e.getY(); 

		updatePosition();
	}

	private void updatePosition() {
		int counter = 0;
		for (int i = 0; i < tetromino.rotationmasks[rotation].length; i++ ) {
			int col[] = tetromino.rotationmasks[rotation][i];
			for (int j = 0; j < col.length; j++) {
				if (col[j] != 0) {
					MVObject cube = children.get(counter); 
					cube.setPosition(this.x + (Cube.DEFAULT_OFFSET * i), 
										this.y + (Cube.DEFAULT_OFFSET * j), 0);
					if (counter == 3) {
						counter = 0;
					}
					counter++;
				}
			}
		}
	}

}